package com.tanhua.api.mongo;

import com.tanhua.domain.mongo.UserLocation;
import com.tanhua.domain.vo.UserLocationVo;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@Service
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveLocation(Double x_longitude, Double y_latitude, String addrStr, Long userId) {
        //根据当前登录人的id查询当前登录人是否存过经纬度
        Query query = new Query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        if(userLocation==null){
            //没存过--新增经纬度
            UserLocation user = new UserLocation();
            user.setId(new ObjectId());   //主键id
            user.setUserId(userId); //当前登录用户id
            GeoJsonPoint location = new GeoJsonPoint(x_longitude, y_latitude);
            user.setLocation(location); //当前登录用户的经纬度
            user.setAddress(addrStr); //所属地址名

            user.setUpdated(System.currentTimeMillis()); //本次更新时间
            mongoTemplate.save(user);
        }else{
            //存过--更新经纬度
            Update update = new Update();
            GeoJsonPoint location = new GeoJsonPoint(x_longitude, y_latitude);
            update.set("location",location);
            update.set("address",addrStr);
            update.set("updated",System.currentTimeMillis());
            update.set("lastUpdated",userLocation.getUpdated());
            mongoTemplate.updateFirst(query,update,UserLocation.class);

        }




    }

    //根据自己的经纬度 查询周边的人
    public List<UserLocationVo> search(Long userId, Integer distance) {
        // 先查询自己
        Query query = new Query(Criteria.where("userId").is(userId));
        UserLocation user = mongoTemplate.findOne(query, UserLocation.class);
        // 以当前自己的经纬度做半径距离查询 搜索附近的用户
        GeoJsonPoint location = user.getLocation();
        //距离
        Distance dt = new Distance(distance/1000, Metrics.KILOMETERS);
        //按经纬度和指定的距离做圆半径搜索
        Circle circle=new Circle(location,dt);
        //查询附近的用户
        Query query2 = new Query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocationList = mongoTemplate.find(query2, UserLocation.class);

        //这个里面注意下：不能返回List<UserLocation>给消费 会报错 GeoJsonPoint没有实现序列化接口 会丢失
        return UserLocationVo.formatToList(userLocationList);
    }
}
